import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
import Layout2 from '@/layout/index2'
import {
  getAdminNav,
  getSettingNav,
  getCodeData,
  getDataSource,
  getExtendEleDisplayList,
  invokeMethod,
  getEmployeeList,
  getAppPreviewNav,
  getAppNav,
  getNavInfo
} from '@/api/common'
import {
  createComponents,
  createRemoteComponents
} from '@admin/packages/table-filter/src/components/extend/utils'
import {
  createCustomComponent
} from '@/utils/index'
import {
  getFormatRoutes,
  getCompressRoutes
} from '@/utils/index'
import {
  createSubRoute
} from '@admin/utils/prototype'
import router from '@/router'
import {
  getAppId
} from '@/utils/index'
import {
  isPreview
} from '@/utils/auth'
import {
  getRoute,
} from '@admin/utils/index'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  menus: []
}

const mutations = {
  // 动态添加主界面路由，需要缓存
  updateAppRouter(state, routes) {
    router.addRoutes(routes)
    state.routes.push(...routes)
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENUE: (state, menus) => {
    state.menus = menus
  },
  ADD_ROUTES: (state, routes) => {
    state.addRoutes.push(...routes)
    state.routes = state.routes.concat(routes)
  },
  ADD_MENUE: (state, menus) => {
    state.menus.push(...menus)
  }
}

const actions = {
  async generateRoutes({ commit }) {
    const codeData = await getCodeData()
    // 处理码表加载
    const dics = codeData.data
    var CodeSource = {}
    if (dics && dics.length) {
      dics.forEach(dic => {
        CodeSource[dic.codeDataTypeId] = dic.codeList.sort((pre, next) => {
          return pre.orderId >= next.orderId ? 1 : -1
        })
      })
      window.$CodeSource = CodeSource
      localStorage.setItem('$CodeSource', JSON.stringify(CodeSource))
    }
    getExtendEleDisplayList({
      webVersion: '1'
    }).then(res => {
      const components = res.data
      try {
        createRemoteComponents(components, {
          fetch: {
            invokeMethod,
            getEmployeeList
          }
        })
      } catch (e) {
        console.error('加载扩展组件失败')
        console.error(e)
      }
    })
    return new Promise(resolve => {
      const appId = getAppId()
      // 根据sessionStorage是否有preview区分是预览还是正常登录
      getAppNav({
        appId: appId
      }).then(res => {
        console.log(res)
        const routes = getFormatRoutes(JSON.parse(JSON.stringify(res.data)))
        routes.push({
          path: '*',
          redirect: '/404',
          hidden: true
        })
        commit('SET_ROUTES', routes)
        commit('SET_MENUE', res.data)
        const compressRoutes = getCompressRoutes(JSON.parse(JSON.stringify(res.data)))
        console.log(compressRoutes)
        resolve(compressRoutes)
      })
    })
  },
  // 创建动态路由
  creteDynamicRoute({
    state,
    commit
  }, {
    pageId,
    parentPageId=''
  }) {
    return new Promise((resolve, reject)=>{
      getNavInfo({
        pageId: pageId
      }).then(res => {
        if (res.success && res.data) {
          commit('ADD_MENUE', [res.data])
          const routes = getFormatRoutes(JSON.parse(JSON.stringify(state.menus)))
          routes.push({
            path: '*',
            redirect: '/404',
            hidden: true
          })
          commit('SET_ROUTES', routes)
          const compressRoutes = getCompressRoutes(JSON.parse(JSON.stringify(state.menus)), '0', 1, (route)=>{
            // 待办详情新增activemenu
            if (parentPageId && route.meta.code == pageId){
              let parentMenu = state.menus.find(i=>i.id == parentPageId)
              if (parentMenu){
                route.meta.activeMenu = parentMenu.vueRouter ? parentMenu.vueRouter : ('/compage/' + parentMenu.id)
              }
            }
          })
          const route = getRoute(pageId)
          router.addRoutes(compressRoutes)
          resolve(route)
        } else {
          reject('页面跳转失败，请检查是否有目标页面的访问权限')
        }
      }).catch((e)=>{
        console.log(e)
        reject('页面跳转失败，请检查是否有目标页面的访问权限')
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
